package helper.sms;

import helper.GlobalConfig;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.libs.WS;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 广州首易信短信发送类.
 */
public class MobsetSmsHelper {

    /**
     * 发送短信.
     */
    public static void sendSMS(List<String> mobiles, String content) {
        Logger.info("LOG01200: mobiles = " + StringUtils.join(mobiles, "/"));

        if (StringUtils.isBlank(GlobalConfig.MOBSET_SMS_CORPID)) {
            Logger.info("LOG01182: 没有配置 广州首易信短信");
            return;
        }

        if (mobiles.size() == 0) {
            Logger.info("LOG01190: no mobiles");
            return;
        }
        if (mobiles.size() > 48) {
            Logger.info("LOG01100: mobiles超过48条，进行拆分后重新发送: mobiles.size() = " + mobiles.size());
            List<List<String>> splitMobileLists = splitList(mobiles, 48);
            for (List<String> splitMobileList : splitMobileLists) {
                sendSMS(splitMobileList, content);
            }
            return;
        }

        if (!content.contains(GlobalConfig.MOBSET_SMS_POSTFIX)) {
            //content += GlobalConfig.MOBSET_SMS_POSTFIX; 不需要加 自动会加上
        }

        String sendNos = StringUtils.join(mobiles, ";");
        String url = "http://web.mobset.com/SDK/Sms_Send.asp?CorpID=" + GlobalConfig.MOBSET_SMS_CORPID
                + "&LoginName=" + GlobalConfig.MOBSET_SMS_USERNAME
                + "&passwd=" + GlobalConfig.MOBSET_SMS_PASSWORD
                + "&send_no=" + sendNos
                + "&msg=" + content
                + "&LongSms=1";
        Logger.info("LOG01120: sendSMS url = " + url);
        WS.HttpResponse httpResponse = WS.withEncoding("GBK").url(url).get();
        if (httpResponse.success()) {
            String result = httpResponse.getString();
            Logger.info("LOG01140: result = " + result);
        } else {
            Logger.info("LOG01150: 发送失败 httpResponse.getStatus() = " + httpResponse.getStatus());
        }
    }

    public static void sendSMS(String mobile, String content) {
        sendSMS(Collections.singletonList(mobile), content);
    }

    private static <T> List<List<T>> splitList(List<T> list, int maxListSize) {
        List<List<T>> splittedList = new ArrayList<List<T>>();
        int itemsRemaining = list.size();
        int start = 0;

        while (itemsRemaining != 0) {
            int end = itemsRemaining >= maxListSize ? (start + maxListSize) : itemsRemaining;

            splittedList.add(list.subList(start, end));

            int sizeOfFinalList = end - start;
            itemsRemaining = itemsRemaining - sizeOfFinalList;
            start = start + sizeOfFinalList;
        }

        return splittedList;
    }

}
